package me.magicall.myblog.front.web.springmvc.controllers;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import me.magicall.coll.CollFactory;
import me.magicall.consts.CommonConst;
import me.magicall.db.dao.Dao;
import me.magicall.db.model.BaseModel.NbBean;
import me.magicall.myblog.util.DaoFactory;
import me.magicall.myblog.util.ModelEnumHolder;
import me.magicall.myblog.util.MyBlogConst;
import me.magicall.myblog.util.U;
import me.magicall.util.Utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @author MaGiCalL
 */
@Controller("listController")
//@RequestMapping(method = RequestMethod.GET, //
//value = { UrlPatternRule.MODEL_NAME + "/list" })
public class ListController {

	@Autowired
	private DaoFactory daoFactory;
	@Autowired
	private ModelEnumHolder modelEnumHolder;

//	@RequestMapping(UrlPatternRule.PAGE)
	public void list(final HttpServletRequest request, final ModelMap modelMap,//
			@PathVariable("modelName") final String modelName,//
			@PathVariable("page") int page) {
		final int pageSize = MyBlogConst.LIST_LIMIT_SIZE;
		if (page < 1) {
			page = 1;
		}
		modelMap.addAttribute("list", getNbBeanDao(modelName).newest((page - 1) * pageSize, pageSize));

		modelMap.addAttribute("modelName", modelName);
		final Class<?> enumClass = getEnumClass(modelName);
		modelMap.addAttribute("fields", enumClass.getEnumConstants());
		modelMap.addAttribute("page", page);
	}

//	@RequestMapping( { UrlPatternRule.IDS, UrlPatternRule.IDS_RANGE })
	public void list(final HttpServletRequest request, final ModelMap modelMap,//
			@PathVariable("modelName") final String modelName,//
			@PathVariable("ids") final String idStr) {
		final int pageSize = MyBlogConst.LIST_LIMIT_SIZE;
		String page;
		final List<? extends Number> ids;
		if (Utils.STR.isEmpty(idStr)) {
			ids = CollFactory.L.seq(1, pageSize);
			page = "1";
		} else if (idStr.indexOf('~') > CommonConst.NOT_FOUND_INDEX) {
			ids = U.parseNumbers(idStr, pageSize);
			page = "1";
		} else {
			final Long i = Utils.LONG.fromString(idStr);
			if (i == null) {
				ids = CollFactory.L.seq(1, pageSize);
				page = "1";
			} else {
				final long start = (i - 1) * pageSize + 1;
				ids = CollFactory.L.seq(start, pageSize);
				page = idStr;
			}
		}
		modelMap.addAttribute("list", getNbBeanDao(modelName).listUsingIds(ids));

		modelMap.addAttribute("modelName", modelName);
		final Class<?> enumClass = getEnumClass(modelName);
		modelMap.addAttribute("fields", enumClass.getEnumConstants());
		modelMap.addAttribute("page", page);
	}

	private Dao<NbBean<?>> getNbBeanDao(final String modelName) {
		return daoFactory.getNbBeanDao(modelName);
	}

	private Class<? extends Enum<?>> getEnumClass(final String modelName) {
		return modelEnumHolder.getEnumClass(modelName);
	}

}
